package com.iwhalecloud.bss.kite.cucc.web.service.accept.handler.attr;

import com.iwhalecloud.bss.kite.client.api.scene.operate.IOperateSceneCommonService;
import com.iwhalecloud.bss.kite.client.dto.DataResult;
import com.iwhalecloud.bss.kite.client.vo.scene.CommonAttrVO;
import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.constant.ServiceOfferConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.common.util.KiteListUtils;
import com.iwhalecloud.bss.kite.common.util.KiteObjectUtils;
import com.iwhalecloud.bss.kite.common.util.KiteStringUtils;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalKeyConsts;
import com.iwhalecloud.bss.kite.cucc.common.constant.LocalServiceOfferConsts;
import com.iwhalecloud.bss.kite.cucc.service.attr.handler.MultipleChargeAttrHandler;
import com.iwhalecloud.bss.kite.cucc.service.pos.handler.CuccPosServiceUtils;
import com.iwhalecloud.bss.kite.cucc.service.util.ProdCateUtil;
import com.iwhalecloud.bss.kite.dataservice.cache.AttrValueCache;
import com.iwhalecloud.bss.kite.dataservice.cache.DcPublicCache;
import com.iwhalecloud.bss.kite.dataservice.entity.AttrValue;
import com.iwhalecloud.bss.kite.dataservice.entity.DcPublic;
import com.iwhalecloud.bss.kite.manager.api.IOperateSceneInstService;
import com.iwhalecloud.bss.kite.manager.api.IQuerySceneInstService;
import com.iwhalecloud.bss.kite.manager.enums.ActionType;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttr;
import com.iwhalecloud.bss.kite.manager.inst.KiteAttrValue;
import com.iwhalecloud.bss.kite.manager.inst.KiteInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteProdInst;
import com.iwhalecloud.bss.kite.manager.inst.KiteSceneInst;
import com.iwhalecloud.bss.kite.service.scene.attr.OperateInstAttrService;
import com.iwhalecloud.bss.kite.web.context.KiteWebContext;
import com.iwhalecloud.bss.kite.web.service.accept.attr.handler.AbstractAttrHandler;
import com.ztesoft.bss.base.entity.StaticAttrDO;
import com.ztesoft.bss.common.util.SpringUtil;
import com.ztesoft.bss.svcability.util.ListUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.stream.Collectors;

@Service
public class OrderNatureAttrHandler extends AbstractAttrHandler {

    @Autowired
    private IQuerySceneInstService querySceneInstService;

    @Autowired
    private IOperateSceneInstService operateSceneInstService;

    @Override
    public void init(CommonAttrVO commonAttr) {
        String sceneInstId = KiteWebContext.getContext().getCurrentSceneInstId();
        KiteSceneInst kiteSceneInst = querySceneInstService.getSceneInst(sceneInstId);
        String serviceOfferId = Optional.ofNullable(kiteSceneInst).map(KiteSceneInst::getServiceOfferId).orElse("");
        KiteAttr orderNatureAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.ORDER_NATURE);
        String custId = KiteWebContext.getContext().getCust().getCustId();
        KiteInst kiteInst = querySceneInstService.getKiteInst(custId, kiteSceneInst.getRootInstType(), kiteSceneInst.getRootInstId());

        if(KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER)) {
            // app甩单补录，订单性质只能为正常单
            String renderOrderType = querySceneInstService.getExtParameterValue(sceneInstId, "renderOrderType");
            boolean flag = (KiteStringUtils.isEqual(renderOrderType, "orderRejection"));

            if(!flag) {
                List<DcPublic> list = DcPublicCache.get("20210719001");
                // 是否五大双线落地方产品订购，订单性质只能为正常单
                flag = (list != null) && list.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(kiteInst.getSpecId(), dcPublic.getCodeb()));
            }
            if (flag) {
                String valueDesc = Optional.ofNullable(AttrValueCache.getAttrValue(commonAttr.getAttrId(), "0")).map(AttrValue::getAttrValueName).orElse("正常单");
                commonAttr.setValue("0");
                commonAttr.setValueDesc(valueDesc);
                commonAttr.setIsEdit(KeyConsts.IFTRUE_F);

                orderNatureAttr.setValue("0");
                orderNatureAttr.setValueDesc(valueDesc);
                orderNatureAttr.setIsEdit(KeyConsts.IFTRUE_F);
                operateSceneInstService.setCommonAttr(sceneInstId, orderNatureAttr);
                setCommonAttr(commonAttr);
                return;
            }
        }

        String nodeCode = querySceneInstService.getExtParameterValue(sceneInstId, "nodeCode");

        // 预销户-重提，五大双线落地方产品-变更-签订，订单性质不能修改
        boolean notModifyAttrFlag = (KiteStringUtils.isEqual(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_PRE_CANCELLATION) && KiteStringUtils.isEqual(nodeCode, "OrderResubmit"));
        if(!notModifyAttrFlag) {
            if(KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_MODIFY) && KiteStringUtils.isEqual(nodeCode, "OrderSigned")) {
                List<DcPublic> list = DcPublicCache.get("20210719001");
                notModifyAttrFlag = (list != null) && list.stream().anyMatch(dcPublic -> KiteStringUtils.isEqual(kiteInst.getSpecId(), dcPublic.getCodeb()));
            }
        }
        if(notModifyAttrFlag) {
            commonAttr.setIsEdit(KeyConsts.IFTRUE_F);
            orderNatureAttr.setIsEdit(KeyConsts.IFTRUE_F);
            operateSceneInstService.setCommonAttr(sceneInstId, orderNatureAttr);
            setCommonAttr(commonAttr);
            return;
        }

        // 获取页面勾选的操作类型，业务变更，操作类型=资料修正，则：订单性质=资料修正单+不能修改
        List<String> serviceOfferIdList = querySceneInstService.getExtParameterValue(sceneInstId, "BUSI_CHANGE_SERVICEOFFERID");
        if(KiteStringUtils.isEqual(commonAttr.getValue(), "8") ||
            (KiteStringUtils.isEqual(serviceOfferId, "2826") && KiteListUtils.isNotEmpty(serviceOfferIdList) && serviceOfferIdList.contains("1080"))) {
            commonAttr.setValue("8");
            commonAttr.setValueDesc("资料修正单");
            commonAttr.setIsEdit(KeyConsts.IFTRUE_F);
            orderNatureAttr.setIsEdit(KeyConsts.IFTRUE_F);

            List<KiteAttrValue> kiteAttrValues = orderNatureAttr.getAttrValues();
            boolean hasNatureAttrValue8 = false;
            for (KiteAttrValue kiteAttrValue : kiteAttrValues) {
                if(KiteStringUtils.isEqual(kiteAttrValue.getAttrValue(), "8")) {
                    hasNatureAttrValue8 = true;
                    break;
                }
            }
            if(!hasNatureAttrValue8) {
                AttrValue attrValue = AttrValueCache.getAttrValue("202103021001", "8");
                List<StaticAttrDO> staticAttrDOList = commonAttr.getAttrValues();
                staticAttrDOList.add(getStaticAttrDO(attrValue));
                commonAttr.setAttrValues(staticAttrDOList);

                kiteAttrValues.add(getKiteAttrValue(attrValue));
                orderNatureAttr.setAttrValues(kiteAttrValues);
            }
        } else {
            List<StaticAttrDO> staticAttrDOList = commonAttr.getAttrValues().stream().filter(staticAttrDO -> !KiteStringUtils.isEqual(staticAttrDO.getAttrValue(), "8")).collect(Collectors.toList());
            commonAttr.setAttrValues(staticAttrDOList);
            List<KiteAttrValue> kiteAttrValues = orderNatureAttr.getAttrValues().stream().filter(kiteAttrValue -> !KiteStringUtils.isEqual(kiteAttrValue.getAttrValue(), "8")).collect(Collectors.toList());
            orderNatureAttr.setAttrValues(kiteAttrValues);
            commonAttr.setIsEdit(KeyConsts.IFTRUE_T);
            orderNatureAttr.setIsEdit(KeyConsts.IFTRUE_T);
        }

        // 五大双线，业务开通，订单性质、开通方式，签订、重提、追单，不可修改
        String cateId = CuccPosServiceUtils.getCateId(sceneInstId, KiteWebContext.getContext().getCustId());
        if(KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())) {
            if(KiteStringUtils.equalsAny(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW, LocalServiceOfferConsts.SERVICE_OFFER_TRANSFER_TO_ORDER)
                || (KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER) && KiteStringUtils.isNotEmpty(nodeCode))) {
                commonAttr.setIsEdit(KeyConsts.IFTRUE_F);
                orderNatureAttr.setIsEdit(KeyConsts.IFTRUE_F);
            }
        }

        // 业务开通订购-信息录入、签订、退单重提，开通单追单-信息录入
        boolean flag = (KiteStringUtils.isEqual(serviceOfferId, ServiceOfferConsts.SERVICE_OFFER_ORDER) && KiteStringUtils.equalsAny(nodeCode, "", "OrderSigned", "OrderAudit", "OrderResubmit")) ||
            (KiteStringUtils.isEqual(serviceOfferId, LocalServiceOfferConsts.SERVICE_OFFER_FOLLOW) && (KiteStringUtils.isEqual(nodeCode, "OrderServiceOpen")));
        // 不是以上环节,或者不是五大双线类产品,去掉补录单
        if(!flag || !KiteStringUtils.equalsAny(cateId, ProdCateUtil.getDoubleLineCateIdForArr())) {
            List<StaticAttrDO> staticAttrDOList = commonAttr.getAttrValues().stream().filter(staticAttrDO -> !KiteStringUtils.isEqual(staticAttrDO.getAttrValue(), "2")).collect(Collectors.toList());
            commonAttr.setAttrValues(staticAttrDOList);
            List<KiteAttrValue> kiteAttrValues = orderNatureAttr.getAttrValues().stream().filter(kiteAttrValue -> !KiteStringUtils.isEqual(kiteAttrValue.getAttrValue(), "2")).collect(Collectors.toList());
            orderNatureAttr.setAttrValues(kiteAttrValues);
        }

        operateSceneInstService.setCommonAttr(sceneInstId, orderNatureAttr);
        setCommonAttr(commonAttr);
    }

    @Override
    public DataResult<Boolean> apply(String sceneInstId, String fieldName, String value, String valueDesc) {
        // 当‘订单性质’选择了绿色工单、补录单，起租方式只能为‘手工起租’，不允许更改
        if (LocalKeyConsts.ORDER_NATURE.equals(fieldName)) {
            KiteAttr startRentWayAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.START_RENT_WAY);
            if (Objects.nonNull(startRentWayAttr)) {
                // 5：绿色工单；2：补录单；8：资料修正单
                if (KiteStringUtils.equalsAny(value, "2", "5", "8")) {
                    startRentWayAttr.setValue("0");
                    startRentWayAttr.setIsEdit("F");
                } else {
                    if(KiteStringUtils.isEmpty(startRentWayAttr.getValue())) {
                        startRentWayAttr.setValue(KiteStringUtils.isEmpty(startRentWayAttr.getOriginValue()) ? startRentWayAttr.getDefaultValue() : startRentWayAttr.getOriginValue());
                    }

                    String fallPlaceStartRentWay = querySceneInstService.getExtParameterValue(sceneInstId, "fallPlaceStartRentWay");
                    if(!KiteStringUtils.isEqual(fallPlaceStartRentWay, KeyConsts.IFTRUE_F)) {
                        startRentWayAttr.setIsEdit("T");
                    }
                }
                String desc = "";
                if (KiteStringUtils.isNotEmpty(startRentWayAttr.getValue())) {
                    desc = Optional.ofNullable(AttrValueCache.getAttrValue(startRentWayAttr.getAttrId(), startRentWayAttr.getValue()))
                        .map(attrVal -> attrVal.getAttrValueDesc()).orElse("");
                }
                startRentWayAttr.setValueDesc(desc);
                SpringUtil.getBean(IOperateSceneCommonService.class).setCommonAttr(sceneInstId, startRentWayAttr);
            }

            this.supplementOrderOperate(sceneInstId, value);

            if(KiteStringUtils.isEqual(value, "8")) {
                KiteAttr orderNatureAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.ORDER_NATURE);
                orderNatureAttr.setIsEdit(KeyConsts.IFTRUE_F);
                operateSceneInstService.setCommonAttr(sceneInstId, orderNatureAttr);
            }
            //订单性质选择补录单时开通方式联动展示“补录资料”且置灰  否则不展示“补录材料”
            KiteAttr openWayAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.OPEN_WAY);
            if(!KiteObjectUtils.isEmpty(openWayAttr)){
                boolean hasBLZL = openWayAttr.getAttrValues().stream().anyMatch(attr -> KiteStringUtils.equals(attr.getAttrValue(), "4"));
                if(KiteStringUtils.isEqual(value, "2")){
                    if(!hasBLZL){
                        openWayAttr.setAttrValues(KiteBeanUtils.copyPropsForList(AttrValueCache.get(openWayAttr.getAttrId()), KiteAttrValue.class));
                    }
                    openWayAttr.setValue("4");
                    openWayAttr.setValueDesc("补录资料");
                    openWayAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    operateSceneInstService.setCommonAttr(sceneInstId, openWayAttr);
                }else if(hasBLZL){
                    openWayAttr.getAttrValues().removeIf(attr->KiteStringUtils.equals(attr.getAttrValue(),"4"));
                    if(KiteStringUtils.equals(openWayAttr.getValue(),"4")){
                        openWayAttr.setValue(openWayAttr.getAttrValues().get(0).getAttrValue());
                        openWayAttr.setValueDesc(openWayAttr.getAttrValues().get(0).getAttrValueDesc());
                        openWayAttr.setIsEdit(KeyConsts.IFTRUE_T);
                    }
                    operateSceneInstService.setCommonAttr(sceneInstId, openWayAttr);
                }
            }
        }
        return super.apply(sceneInstId, fieldName, value, valueDesc);
    }

    /**
     * 订单性质补录单联动处理
     * 1.如果是补录单，则订单信息模块起租方式只展示手工起租，不展示自动起租
     * 2.如果订单性质为补录单，追单、退单重提、订单签订不能修改订单性质
     * 3.订单性质=补录单，是否多方收费=否，不可修改（五大双线）
     */
    private void supplementOrderOperate(String sceneInstId, String value) {
        // 订单性质（2：补录单）
        KiteAttr orderNatureAttr = querySceneInstService.getCommonAttr(sceneInstId, LocalKeyConsts.ORDER_NATURE);
        // 当前值=补录单，或上次的值=补录单
        if(KiteStringUtils.equalsAny("2", orderNatureAttr.getValue(), value)) {
            String catagoryId = CuccPosServiceUtils.getCateId(sceneInstId, KiteWebContext.getContext().getCustId());
            // 是否五大双线
            if(KiteStringUtils.equalsAny(catagoryId, ProdCateUtil.getDoubleLineCateIdForArr())) {
                boolean flag = KiteStringUtils.isEqual(value, "2");

                // 业务号码
                KiteAttr serialNumberAttr = querySceneInstService.getCommonAttr(sceneInstId, "business_number");
                if(KiteStringUtils.isEmpty(serialNumberAttr.getOriginValue()) && KiteStringUtils.isNotEmpty(serialNumberAttr.getValue())) {
                    // 记录接口返回的业务号码，选择补录单手输业务号码，若再选其他类型，则重置业务号码为接口返回值
                    serialNumberAttr.setOriginValue(serialNumberAttr.getValue());
                }
                if(flag) {
                    serialNumberAttr.setIsEdit(KeyConsts.IFTRUE_T);
                } else {
                    serialNumberAttr.setIsEdit(KeyConsts.IFTRUE_F);
                    String serialNumber = serialNumberAttr.getOriginValue();
                    serialNumberAttr.setValue(serialNumber);
                    serialNumberAttr.setValueDesc(serialNumber);
                }
                operateSceneInstService.setCommonAttr(sceneInstId, serialNumberAttr);
                operateSceneInstService.setCommonAttrValue(sceneInstId, "business_number", serialNumberAttr.getValue(), serialNumberAttr.getValue());

                // 查询需要联动的字段
                List<DcPublic> dcPublics = DcPublicCache.getByPkey("2021050701", catagoryId);
                if(!ListUtil.isEmpty(dcPublics)) {
                    OperateInstAttrService operateInstAttrService = SpringUtil.getBean(OperateInstAttrService.class);
                    List<KiteProdInst> prodInsts = querySceneInstService.listProdInsts(sceneInstId);
                    prodInsts.forEach(prodInst -> {
                        KiteAttr kiteAttr;
                        for (DcPublic dcPublic : dcPublics) {
                            kiteAttr = prodInst.getAttr(dcPublic.getPcode());
                            if(Objects.nonNull(kiteAttr)) {
                                if(flag) {
                                    kiteAttr.setIsNull(dcPublic.getCodea());
                                    kiteAttr.setIsEdit(dcPublic.getCodeb());
                                } else {
                                    kiteAttr.setIsNull(KeyConsts.IFTRUE_T);
                                    kiteAttr.setIsEdit(KeyConsts.IFTRUE_F);
                                    kiteAttr.setValue(null);
                                    kiteAttr.setValueDesc(null);
                                }
                                operateInstAttrService.setAttrValue(prodInst, kiteAttr.getFieldName(), kiteAttr.getValue(), sceneInstId, null);
                            }
                        }
                    });
                }

                // 是否多方收费，非跨域不可修改，选择装机地址后进行判断
                KiteSceneInst sceneInst = querySceneInstService.getSceneInst(sceneInstId);
                KiteProdInst prodInst = querySceneInstService.listProdInstsFromOfferInst(sceneInst.getCustId(), sceneInst.getRootInstId()).stream()
                    .filter(kiteProdInst -> !KiteStringUtils.equalsAny(kiteProdInst.getActionType().name(), ActionType.X.name(), ActionType.D.name()))
                    .findFirst().orElse(null);
                if(Objects.nonNull(prodInst)) {
                    KiteAttr isMultipleChargeAttr = prodInst.getAttr("210008004");
                    if(Objects.nonNull(isMultipleChargeAttr)) {
                        MultipleChargeAttrHandler multipleChargeAttrHandler = SpringUtil.getBean(MultipleChargeAttrHandler.class);
                        multipleChargeAttrHandler.setMultipleChargeAttr(isMultipleChargeAttr, prodInst, sceneInstId, value);
                    }
                }
            }
        }
    }

    // 订单性质枚举值-资料修正单
    private static KiteAttrValue getKiteAttrValue(AttrValue attrValue) {
        KiteAttrValue kiteAttrValue = new KiteAttrValue();
        if(attrValue != null) {
            kiteAttrValue.setAttrValueId(attrValue.getAttrValueId());
            kiteAttrValue.setAttrId(attrValue.getAttrId());
            kiteAttrValue.setAttrValue(attrValue.getAttrValue());
            kiteAttrValue.setAttrValueName(attrValue.getAttrValueName());
        } else {
            kiteAttrValue.setAttrId("202103021001");
            kiteAttrValue.setAttrValue("8");
            kiteAttrValue.setAttrValueName("资料修正单");
        }
        return kiteAttrValue;
    }

    // 订单性质枚举值-资料修正单
    private static StaticAttrDO getStaticAttrDO(AttrValue attrValue) {
        StaticAttrDO staticAttrDO = new StaticAttrDO();
        if(attrValue != null) {
            staticAttrDO.setAttrValueId(attrValue.getAttrValueId());
            staticAttrDO.setAttrId(attrValue.getAttrId());
            staticAttrDO.setAttrValue(attrValue.getAttrValue());
            staticAttrDO.setAttrValueDesc(attrValue.getAttrValueName());
        } else {
            staticAttrDO.setAttrId("202103021001");
            staticAttrDO.setAttrValue("8");
            staticAttrDO.setAttrValueDesc("资料修正单");
        }
        return staticAttrDO;
    }
}
